const express=require('express')
const pool=require('../pool')
const router=express.Router()

// 查询所有订单
router.get('/list',(req,res,next)=>{
    pool.query('select * from order1',(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询所有订单成功',data:r})
    })
})

// 通过id查询订单
router.get('/queryById',(req,res,next)=>{
    let obj=req.query
    let orderId=obj.orderId
    pool.query('select * from order1 where orderId=?',[orderId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询指定订单成功',data:r})
    })
})

// 删除订单
router.get('/delete',(req,res,next)=>{
    let obj=req.query
    let orderId=obj.orderId
    pool.query('delete from order1 where orderId=?',[orderId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'删除订单成功',data:r})
    })
})

// 增加订单
router.post('/add',(req,res,next)=>{
    let obj=req.body
    pool.query('insert into order1 set ?',[obj],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'增加订单成功',data:r})

    })
})

// 修改订单
router.post('/modify',(req,res,next)=>{
    let obj=req.body
    pool.query('update order1 set ? where orderId=?',[obj,obj.orderId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'修改订单成功',data:r})
    })
})

// 分页查询
router.get('/page',(req,res,next)=>{
    let obj=req.query;
    let pno=obj.pno;
    let pcount=obj.pcount;
    let start =(pno-1)*pcount
    let end =Number(pcount)
    pool.query('select * from order1 limit ?,?;select count(*) sum from order1',[start,end],(err,r)=>{
        if(err){
            return next(err)
        }
        let total=r[1][0].sum
        let pages= Math.ceil(total/pcount)
        res.send({code:200,msg:'分页查询成功',pno,pcount,total,pages,data:r})
    })
})

// 查所有订单数量
router.get('/count',(req,res,next)=>{
    pool.query('select count(*) sum from order1',(err,r)=>{
        if(err){
            return next(err)
        }
        let total=r[0].sum
        res.send({code:200,msg:'查询总订单数成功',total,data:r})
    })
})

module.exports=router

